<?php
	/**
    * 生成随即字符串
    * 创建人:  Zhou Hailong
    * 创建时间: 2014-10-16 10:43
    * 最后修改人：
    * 最后修改时间：
    * @param int $min_length 最小生成长度
    * @param int $max_length 最大生成长度
    * @param string $type 生成类型[all：无限制，number：只生成数字格式的字符串，abc：只生成英文字母格式的字符串]
    */
    function create_rand_str($min_length = 1, $max_length = 8, $type = 'all'){
        $string = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
        if($max_length < $min_length) $max_length = $max_length + $min_length;
        $str_length = rand($min_length, $max_length);
        if($type == 'all'){
            $start_rand = 0;
            $end_rand = strlen($string) - 1;
        }elseif($type == 'number'){
            $start_rand = 52;
            $end_rand = strlen($string) - 1;
        }elseif($type == 'abc'){
            $start_rand = 0;
            $end_rand = strlen($string) - 11;
        }else{
            return false;
        }
        $str = '';
        for ($i=0; $i < $str_length; $i++) { 
            $str .= $string[ mt_rand($start_rand, $end_rand) ];
        }
        return $str;
    }
	
	function get_menu_title_by_menu_url($menu_url){
		$CI =& get_instance();
		$CI->load->model("privileges");
		$info = $CI->privileges->get_field_by_where("menu_title", "menu_url='{$menu_url}'");
		return isset($info['menu_title']) ? $info['menu_title'] : '';
	}

	if (!function_exists('message')) { 
	    function show_message($target_url, $content="操作成功", $delay_time = 3) {
	        $_CI = &get_instance();
	        $data = array(
			            'target_url' => $target_url,
			            'content' => $content,
			            'delay_time' => $delay_time
			        	);
	        $_CI->smarty->display('show_message.html', $data);
	    }
	}

	function is_ajax_request(){
		if ( isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest' ) {
		    return true;
		} else {
		    return false;
		}
	}

	/**
		* 函数功能介绍：根据原图名称获取最小缩略图名称和路径
		* 创建人: 	Yang Ningshu
		* 创建时间: 2014-09-02 16:20L
		* 最后修改人：Zhou Hailong
		* 最后修改时间：2014-09-12 11:00
		* @param image_url var_char
		* @return array
	*/
	function get_thumb_image_url($image_url){
		if($image_url){
			if(strstr($image_url,'data/')){
				return $image_url;exit;
			}
			if(strstr($image_url,'images/')){
				return $image_url;exit;
			}
			if(strstr($image_url,'http://')){
				return $image_url;exit;
			}
			$image_path_name = explode('/', $image_url);
			$image_name = array_pop($image_path_name);
			$image_name = explode('.', $image_name);
			$name = array_shift($image_name);
			if(isset($image_path_name[3])){
				$image_url = $image_path_name[1].'/'.$image_path_name[2].'/'.$image_path_name[3].'/small_thumb/'.$name.'_thumb.' . end($image_name);
			}
			if($image_url){
				return $image_url;
			}else{
				return false;
			}
		}
	}

	function get_field_by_where($table, $fileds='*', $where='1=1'){
        $CI =& get_instance();
        $sql = "SELECT $fileds FROM {$CI->db->dbprefix}{$table} WHERE $where";
        $result = $CI->db->query($sql)->row_array();
        return $result;
    }

    function get_list_field_by_where($table, $fileds='*', $where='1=1'){
        $CI =& get_instance();
        $sql = "SELECT $fileds FROM {$CI->db->dbprefix}{$table} WHERE $where";
        $result = $CI->db->query($sql)->result_array();
        return $result;
    }

    function echo_filed_by_where($table, $filed='*', $where='1=1'){
        $CI =& get_instance();
        $sql = "SELECT $filed FROM {$CI->db->dbprefix}{$table} WHERE $where";
        $result = $CI->db->query($sql)->row_array();
        echo $result[$filed];
    }

    /**
     * 下载远程文件
     * @param string $url 文件的绝对url
     * @param string $filepath 文件的完整储存路径 ，此函数会自动根据图片url和http头信息确定图片的后缀名
     * @return mixed 下载成功返回文件路径，下载失败则返回false
     */
    function downloadFile($url, $filepath, $file_name) {
        //服务器返回的头信息
        $responseHeaders = array();
        //原始图片名
        $originalfilename = '';
        //图片的后缀名
        $ext = '';
        $ch = curl_init($url);
        //设置curl_exec返回的值包含Http头
        curl_setopt($ch, CURLOPT_HEADER, 1);
        //设置curl_exec返回的值包含Http内容
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);       
        //设置抓取跳转（http 301，302）后的页面
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        //设置最多的HTTP重定向的数量
        curl_setopt($ch, CURLOPT_MAXREDIRS, 2);
 
        //服务器返回的数据（包括http头信息和内容）
        $html = curl_exec($ch);
        //获取此次抓取的相关信息
        $httpinfo = curl_getinfo($ch);
        curl_close($ch);
        if ($html !== false) {
            //分离response的header和body，由于服务器可能使用了302跳转，所以此处需要将字符串分离为 2+跳转次数 个子串
            $httpArr = explode("\r\n\r\n", $html, 2 + $httpinfo['redirect_count']);
            //倒数第二段是服务器最后一次response的http头
            $header = $httpArr[count($httpArr) - 2];
            //倒数第一段是服务器最后一次response的内容
            $body = $httpArr[count($httpArr) - 1];
            $header.="\r\n";
 
            //获取最后一次response的header信息
            preg_match_all('/([a-z0-9-_]+):\s*([^\r\n]+)\r\n/i', $header, $matches);
            if (!empty($matches) && count($matches) == 3 && !empty($matches[1]) && !empty($matches[1])) {
                for ($i = 0; $i < count($matches[1]); $i++) {
                    if (array_key_exists($i, $matches[2])) {
                        $responseHeaders[$matches[1][$i]] = $matches[2][$i];
                    }
                }
            }
            //获取图片后缀名
            if (0 < preg_match('{(?:[^\/\\\\]+)\.(jpg|jpeg|gif|png|bmp|mp4)$}i', $url, $matches)) {
                $originalfilename = $matches[0];
                $ext = $matches[1];
            } else {
                if (array_key_exists('Content-Type', $responseHeaders)) {
                    if (0 < preg_match('{image/(\w+)}i', $responseHeaders['Content-Type'], $extmatches)) {
                        $ext = $extmatches[1];
                    }
                }
            }
            
            //保存文件
            if (!empty($ext)) {
                if (!file_exists($filepath)) {
                    @mkdir($filepath, 0755);
                }
                if(! file_exists('uploads')){
                    mkdir('uploads', 0777);
                }
                if(! file_exists('uploads/images')){
                    mkdir('uploads/images', 0777);
                }
                if(! file_exists('uploads/images/'.date("Ymd"))){
                    mkdir('uploads/images/'.date("Ymd"), 0777);
                }
                $filepath .= $file_name . ".$ext";
                //如果目录不存在，则先要创建目录
                // CFiles::createDirectory(dirname($filepath));
                $local_file = fopen($filepath, 'w');
                if (false !== $local_file) {
                    if (false !== fwrite($local_file, $body)) {
                        fclose($local_file);
                        $sizeinfo = getimagesize($filepath);
                        // return array('filepath' => $filepath, 'width' => $sizeinfo[0], 'height' => $sizeinfo[1], 'orginalfilename' => $originalfilename, 'filename' => pathinfo($filepath, PATHINFO_BASENAME));
                        return $filepath;
                    }
                }
            }
        }
        return false;
    }

    function getfirstchar($s0){
        if(!is_numeric($s0{0})){
            $fchar = ord($s0{0});
            if($fchar >= ord("A") and $fchar <= ord("z") )return strtoupper($s0{0});
            $s1 = iconv("UTF-8","gb2312", $s0);
            $s2 = iconv("gb2312","UTF-8", $s1);
            if($s2 == $s0){
                $s = $s1;
            }else{
                $s = $s0;
            }
            $asc = ord($s{0}) * 256 + ord($s{1}) - 65536;
            if($asc >= -20319 and $asc <= -20284) return "A";
            if($asc >= -20283 and $asc <= -19776) return "B";
            if($asc >= -19775 and $asc <= -19219) return "C";
            if($asc >= -19218 and $asc <= -18711) return "D";
            if($asc >= -18710 and $asc <= -18527) return "E";
            if($asc >= -18526 and $asc <= -18240) return "F";
            if($asc >= -18239 and $asc <= -17923) return "G";
            if($asc >= -17922 and $asc <= -17418) return "I";
            if($asc >= -17417 and $asc <= -16475) return "J";
            if($asc >= -16474 and $asc <= -16213) return "K";
            if($asc >= -16212 and $asc <= -15641) return "L";
            if($asc >= -15640 and $asc <= -15166) return "M";
            if($asc >= -15165 and $asc <= -14923) return "N";
            if($asc >= -14922 and $asc <= -14915) return "O";
            if($asc >= -14914 and $asc <= -14631) return "P";
            if($asc >= -14630 and $asc <= -14150) return "Q";
            if($asc >= -14149 and $asc <= -14091) return "R";
            if($asc >= -14090 and $asc <= -13319) return "S";
            if($asc >= -13318 and $asc <= -12839) return "T";
            if($asc >= -12838 and $asc <= -12557) return "W";
            if($asc >= -12556 and $asc <= -11848) return "X";
            if($asc >= -11847 and $asc <= -11056) return "Y";
            if($asc >= -11055 and $asc <= -10247) return "Z";
        }
        return "#";
    }
	
	
    //判断url是否带是远程路径。
    function get_http_url($url=0,$path_prefix=''){
        if($url == '') return $url;
        if(strstr($url, 'http://')){
            if(strstr($url, 'qiniudn')){
                $CI =& get_instance();
                $CI->config->load('img_config', TRUE);
                $data = $CI->config->item('data', 'img_config');
                return $url . '?imageMogr2/thumbnail/'.$data['small_thumb']['width'].'x'.$data['small_thumb']['height'];
            }
            return $url;
        }else{
			if($path_prefix){
				$url = $path_prefix.$url;	
			}else{
				$url = config_item('api_path').$url;
			}
            return $url;
        }
    }

    //表情转换
    function get_emoji_by_text($str = '') {
        $CI =& get_instance();
        $CI->config->load('emoji_config');
        $EMOJI_CFG  = $CI->config->item('EMOJI_CFG');
        return str_replace(array_keys($EMOJI_CFG), $EMOJI_CFG, rawurldecode($str));
        
    }

    //判断视频url是否带是远程路径。
    function get_video_http_url($url=0){
        if($url == '') return $url;
        if(strstr($url, 'http://')){
            return $url;
        }else{
            $url = config_item('api_path').$url;
            return $url;
        }
    }

     function get_qiniu_token($type = 'VIDEO', $video_name = '') {
        require_once ("third_party/qiniu/lib/rs.php");
        if($video_name == '') $video_name = time() . '.mp4';
        $CI =& get_instance();
        $CI->config->load('qiniu_config');
        $qiniu_config  = $CI->config->item('THINK_SDK_QINIU');       
        Qiniu_SetKeys ( $qiniu_config['APP_KEY'], $qiniu_config['APP_SECRET'] );
        $putPolicy = new Qiniu_RS_PutPolicy ( $qiniu_config[$type]['UPLOAD_DOMAIN'] );
        /*if($video_name != ''){
            $putPolicy->SaveKey = $video_name;
        }*/
        if($type == 'VIDEO'){
            $putPolicy->PersistentOps = 'vframe/jpg/offset/5|saveas/' . base64_encode($qiniu_config['VIMG']['UPLOAD_DOMAIN'] . ':' . md5(rand(100001, 100000009) . $video_name));
            // $putPolicy->Transform = 'avthumb/mp4/vcodec/copy/acodec/copy';
            $putPolicy->PersistentPipeline = "video-moov";
        }
        $upToken = $putPolicy->Token ( null );
        return $upToken;
    }

    function get_qiniu_url($url=0){
        if(strstr($url, 'http://') || $url == ''){
            return $url;
        }else{
            $CI =& get_instance();
            $CI->config->load('qiniu_config');
            $qiniu_config = $CI->config->item('THINK_SDK_QINIU');
            $url = 'http://' . $qiniu_config['VIMG']['DOMAIN_PREFIX'] . '.' . $qiniu_config['VIMG']['DOMAIN'] . '/' .$url;
            return $url;
        }
    }

    function delete_qiniu_data($key, $type = "VIDEO"){
        require_once ("third_party/qiniu/lib/rs.php");
        $CI =& get_instance();
        $CI->config->load('qiniu_config');
        $qiniu_config  = $CI->config->item('THINK_SDK_QINIU');       
        Qiniu_SetKeys ( $qiniu_config['APP_KEY'], $qiniu_config['APP_SECRET'] );
        $client = new Qiniu_MacHttpClient(null);
        $err = Qiniu_RS_Delete($client, 'damivideoimg', $key);
        /*if ($err !== null) {
            var_dump($err);
        } else {
            echo "Success!";
        }*/
    }
    
    function send_sms($mobile,$msg){
        $CI =& get_instance();
        $CI->config->load('qiniu_config');
        
        $smsHLAccount 	= $CI->config->item('smsHLAccount');
		$smsHLPassword 	= $CI->config->item('smsHLPassword');
		$smsHLSendUrl	= $CI->config->item('smsHLSendUrl');
		$smsHLCooperid	= $CI->config->item('smsHLCooperid');
		
		$msg = mb_convert_encoding($msg, "GBK", "UTF-8"); 
		$URL =$smsHLSendUrl.'?username='.$smsHLAccount.'&password='.$smsHLPassword.'&message='.rawurlencode($msg).'&phone='.$mobile.'&epid='.$smsHLCooperid.'&linkid=&subcode=';
		$retMsg = file_get_contents($URL);
		if($retMsg == '00' ){
			return true;
		}
		
		return false;
    }

    //批量删除体检项目
    function delete_data($ids, $table){
        $CI =& get_instance();
        $ids = implode(",",$ids);
        $sql = "DELETE FROM {$CI->db->dbprefix}{$table} WHERE id in($ids)";
        $CI->db->query($sql);
    }

    /*过滤html标签*/  
    function cleanhtml($str,$tags='<img>'){//过滤时默认保留html中的<a><img>标签  
        $search = array(  
                        '@<script[^>]*?>.*?</script>@si',  // Strip out javascript  
    /*                      '@<[\/\!]*?[^<>]*?>@si',            // Strip out HTML tags*/  
                        '@<style[^>]*?>.*?</style>@siU',    // Strip style tags properly   
                        '@<![\s\S]*?--[ \t\n\r]*>@'         // Strip multi-line comments including CDATA   
        );   
        $str = preg_replace($search, '', $str);  
        $str = strip_tags($str,$tags);  
        return $str;  
    }
    //将中文符号转换成英文符号
    // 第一个参数：传入要转换的字符串
    // 第二个参数：取0，半角转全角；取1，全角到半角
    function make_semiangle($str, $args2 = 1) {
        $DBC = Array(
            '０' , '１' , '２' , '３' , '４' ,
            '５' , '６' , '７' , '８' , '９' ,
            'Ａ' , 'Ｂ' , 'Ｃ' , 'Ｄ' , 'Ｅ' ,
            'Ｆ' , 'Ｇ' , 'Ｈ' , 'Ｉ' , 'Ｊ' ,
            'Ｋ' , 'Ｌ' , 'Ｍ' , 'Ｎ' , 'Ｏ' ,
            'Ｐ' , 'Ｑ' , 'Ｒ' , 'Ｓ' , 'Ｔ' ,
            'Ｕ' , 'Ｖ' , 'Ｗ' , 'Ｘ' , 'Ｙ' ,
            'Ｚ' , 'ａ' , 'ｂ' , 'ｃ' , 'ｄ' ,
            'ｅ' , 'ｆ' , 'ｇ' , 'ｈ' , 'ｉ' ,
            'ｊ' , 'ｋ' , 'ｌ' , 'ｍ' , 'ｎ' ,
            'ｏ' , 'ｐ' , 'ｑ' , 'ｒ' , 'ｓ' ,
            'ｔ' , 'ｕ' , 'ｖ' , 'ｗ' , 'ｘ' ,
            'ｙ' , 'ｚ' , '－' , '　' , '：' ,
            '．' , '，' , '／' , '％' , '＃' ,
            '！' , '＠' , '＆' , '（' , '）' ,
            '＜' , '＞' , '＂' , '＇' , '？' ,
            '［' , '］' , '｛' , '｝' , '＼' ,
            '｜' , '＋' , '＝' , '＿' , '＾' ,
            '￥' , '￣' , '｀', '÷', '×'
        );

        $SBC = Array( // 半角
            '0', '1', '2', '3', '4',
            '5', '6', '7', '8', '9',
            'A', 'B', 'C', 'D', 'E',
            'F', 'G', 'H', 'I', 'J',
            'K', 'L', 'M', 'N', 'O',
            'P', 'Q', 'R', 'S', 'T',
            'U', 'V', 'W', 'X', 'Y',
            'Z', 'a', 'b', 'c', 'd',
            'e', 'f', 'g', 'h', 'i',
            'j', 'k', 'l', 'm', 'n',
            'o', 'p', 'q', 'r', 's',
            't', 'u', 'v', 'w', 'x',
            'y', 'z', '-', ' ', ':',
            '.', ',', '/', '%', '#',
            '!', '@', '&', '(', ')',
            '<', '>', '"', '\'','?',
            '[', ']', '{', '}', '\\',
            '|', '+', '=', '_', '^',
            '$', '~', '`', '/', '*'
        );

        if ($args2 == 0) {
            return str_replace($SBC, $DBC, $str);  // 半角到全角
        } else if ($args2 == 1) {
            return str_replace($DBC, $SBC, $str);  // 全角到半角
        } else {
            return false;
        }
    }

    function formula($str){
        $str_len  =  strlen($str);
        for($i=0;  $i < $str_len;  $i++)  {
            $array[] = substr($str, $i, 1);
        }
        foreach($array  as  $key  =>  $value)  {
            if(is_numeric($value)  ||  $value  ==  '.'){
                @$gg .= $value;
            }else{
                @$gg .= '@'.$value.'@';
            }
        }
        $gg = str_replace("@@", "@", $gg);
        $str_array = explode('@', $gg);
        foreach ($str_array as $key => $value) {
            if($value == '' || $value == ' '){
                unset($str_array[$key]);
            }
        }
        return array_values($str_array);
    }
